package com.hzeport.bgs22emduty.inbound.api;

import cn.hutool.core.io.FileUtil;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.entity.Appendix;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.AppendixRepository;
import com.hzeport.bgs22emduty.vo.file.FileVO;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.poi.util.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@RestController
@AllArgsConstructor
@RequestMapping("/filels")
@Api(value = "filels", tags = "文件上传和下载-大屏用")
@Slf4j
@CrossOrigin
public class FileLSController {

    private final SystemConfig systemConfig;

    @ApiOperation(value = "下载", notes = "下载")
    @GetMapping("/download")
    public void download(HttpServletResponse response, @RequestParam String fileName) throws IOException {
//        File file = new File(systemConfig.getFileUrl() + fileName);
        File file = FileUtils.getFile(systemConfig.getFileUrl() + fileName);
        if(!file.exists()){
            return;
        }
//        FileInputStream fileInputStream = new FileInputStream(file);
        //通用文件contentType
        if (fileName.contains("pdf")) {
            response.setContentType("application/pdf;charset=utf-8");
        }
        response.setHeader("Content-Disposition","inline;filename="+URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        try(InputStream inputStream = new FileInputStream(file)){
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        }catch (IOException e){
            log.error("记录到异常", e);
        }

//        ServletOutputStream outputStream = response.getOutputStream();
//        byte[] bytes = new byte[1024];
//        int len;
//        while ((len = fileInputStream.read(bytes)) != -1){
//            outputStream.write(bytes,0,len);
//        }
//        outputStream.flush();
//        outputStream.close();

    }
}
